package com.gxa.uhome.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxa.uhome.pojo.Shipper;
import com.gxa.uhome.service.LogService;
import com.gxa.uhome.service.ShipperService;
import com.gxa.uhome.service.TranService;
import com.gxa.uhome.util.JsonResult;
import com.gxa.uhome.util.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: XHZ
 * @Date: 16:18 2021/6/5
 */
@RequestMapping("/shipper")
@RestController
@Api(tags = "Shipper配送员模块", produces = "application/json;charset=utf-8")
@CrossOrigin
public class ShipperController {
    @Resource
    ShipperService shipperService;
    @Resource
    TranService tranService;
    @Resource
    LogService logService;

    @GetMapping("/all")
    @ApiOperation(value = "查询所有配送员信息", httpMethod = "GET")
    public JsonResult selectShipperByPage(@RequestParam(value = "isUse",required = false) Boolean isUse,
                                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                                          @RequestParam(value = "size", defaultValue = "8") Integer size) {
        List<Shipper> shippers = shipperService.selectByPage(isUse, (page - 1) * size, size);
        JsonResult jsonResult = new JsonResult();
        if (shippers != null) {
            jsonResult.setCode("1");
            jsonResult.setMsg("查询成功");
            jsonResult.setData(shippers);
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("查询失败");
        }
        return jsonResult;
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加配送员", httpMethod = "POST")
    @ApiImplicitParams(@ApiImplicitParam(name = "map", value = "有两个对象，一个配送员对象shipper，一个交通工具列表tranList", paramType = "body"))
    @Transactional
    public JsonResult addShipper(@RequestBody Map<String, Object> map) {
        String jsonString = JSON.toJSONString(map.get("shipper"));
        Shipper shipper = JSON.parseObject(jsonString, Shipper.class);
        Integer insertShipper = shipperService.insert(shipper);
        Integer lastId = shipperService.selectMaxId();
        Integer insertTran = tranService.insert(lastId, (List<String>) map.get("tranList"));
        JsonResult jsonResult = new JsonResult();
        if (insertShipper == 1 && lastId != null && insertTran != null) {
            jsonResult.setCode("1");
            jsonResult.setMsg("添加成功");
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("添加失败");
        }
        return jsonResult;
    }

    @GetMapping("/like")
    @ApiOperation(value = "配送员模糊搜索", httpMethod = "GET")
    @ApiImplicitParams(@ApiImplicitParam(name = "nameOrPhone", value = "名称或电话", dataType = "string", paramType = "query"))
    public JsonResult selectLikeByPage(@RequestParam(value = "nameOrPhone") String nameOrPhone,
                                       @RequestParam(value = "isUse") Boolean isUse,
                                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "size", defaultValue = "8") Integer size) {
        List<Shipper> shippers = shipperService.selectLikeByPage(nameOrPhone, isUse, (page - 1) * size, size);
        JsonResult jsonResult = new JsonResult();
        if (shippers != null) {
            jsonResult.setCode("1");
            jsonResult.setMsg("查询成功");
            jsonResult.setData(shippers);
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("查询失败");
        }
        return jsonResult;
    }

    @PostMapping("/del")
    @ApiOperation(value = "根据电话删除配送员", httpMethod = "POST")
    @ApiImplicitParams(@ApiImplicitParam(name = "phone", value = "电话", dataType = "string", paramType = "query"))
    public JsonResult deleteByPhone(@RequestParam(value = "phone") String phone, HttpSession httpSession) {
        Shipper shipper = shipperService.selectNameByPhone(phone);
        Integer delete = shipperService.deleteByPhone(phone);
        Integer adminId = (Integer) httpSession.getAttribute("AdminId");
        JsonResult jsonResult = new JsonResult();
        if (delete == 1) {
            jsonResult.setCode("1");
            jsonResult.setMsg("删除成功");
            logService.insert("配送员删除", adminId, "删除了配送员" + shipper.getName());
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("删除失败");
        }
        return jsonResult;
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改配送员信息", httpMethod = "POST")
    public JsonResult updateShipper(@RequestBody Shipper shipper, HttpSession httpSession) {
        Integer update = shipperService.update(shipper);
        Integer adminId = (Integer) httpSession.getAttribute("AdminId");
        JsonResult jsonResult = new JsonResult();
        if (update == 1) {
            jsonResult.setCode("1");
            jsonResult.setMsg("修改成功");
            logService.insert("配送员修改", adminId, "修改了" + shipper.getName() + "信息");
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("修改失败");
        }
        return jsonResult;
    }

    @PostMapping("/updateIsUse")
    @ApiOperation(value = "冻结解冻配送员", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "配送员id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "isUse", value = "配送员冻结", dataType = "Boolean", paramType = "query")
    })
    public JsonResult updateIsUse(@RequestParam Integer id, @RequestParam Boolean isUse) {
        Integer updateIsUseById = shipperService.updateIsUseById(id, isUse);
        JsonResult jsonResult = new JsonResult();
        if (updateIsUseById == 1) {
            jsonResult.setCode("1");
            jsonResult.setMsg("修改成功");
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("修改失败");
        }
        return jsonResult;
    }

    @GetMapping("/count")
    @ApiOperation(value = "查询配送员数量", httpMethod = "GET")
    public JsonResult selectShipperCount() {
        Integer count = shipperService.count();
        JsonResult jsonResult = new JsonResult();
        if (count != null) {
            jsonResult.setCode("1");
            jsonResult.setMsg("查询成功");
            jsonResult.setData(count);
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("查询失败");
        }
        return jsonResult;
    }

    @PostMapping("/login")
    @ApiOperation(value = "登录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "配送员电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pwd", value = "配送员密码", dataType = "String", paramType = "query")
    })
    public JsonResult login(@RequestParam String phone, @RequestParam String pwd) {
        Shipper shipper = shipperService.loginByPhone(phone, pwd);
        JsonResult jsonResult = new JsonResult();
        if (MD5Util.encode(pwd).equalsIgnoreCase(shipper.getPwd())) {
            jsonResult.setCode("1");
            jsonResult.setMsg("用户名密码匹配成功");
            jsonResult.setData(shipper);
        } else {
            jsonResult.setCode("0");
            jsonResult.setMsg("用户名或密码错误");
        }
        return jsonResult;
    }

    @PostMapping("/upload")
    @ApiOperation(value = "excel表导入进数据库", httpMethod = "POST")
    public JsonResult upload(@RequestParam("file") MultipartFile file) throws IOException {

        InputStream in = null;
        try {
            //将file转InputStream
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将InputStream转XLSX对象（即表格对象）
        assert in != null;
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);
        //获取表格的第一页
        XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
        //获取该页有多少数据
        int rowNum = xssfSheet.getLastRowNum();
        System.out.println(rowNum);
        for (int i = 1; i <= rowNum; i++) {
            //获取当前行
            XSSFRow xssfRow = xssfSheet.getRow(i);

            //由于学号是纯数字，默认纯数字是以double传的，写进据库会变成科学计数法格式的，需要改为以string传进来
            xssfRow.getCell(3).setCellType(CellType.STRING);

            //以此获得该行的所有单元格
            String name = xssfRow.getCell(0).toString();
            String phone = xssfRow.getCell(1).toString();
            String sex = xssfRow.getCell(2).toString();
            Integer age = Integer.valueOf(xssfRow.getCell(3).toString());
            String licenseId = xssfRow.getCell(4).toString();
            String cardId = xssfRow.getCell(5).toString();
            String driverId = xssfRow.getCell(6).toString();
            String origin = xssfRow.getCell(7).toString();
            String tranVan = xssfRow.getCell(8).toString();
            String tranElectricMotor = xssfRow.getCell(9).toString();

            //将数据写入实体类
            Shipper shipper = new Shipper();
            shipper.setName(name);
            shipper.setPhone(phone);
            shipper.setSex(sex);
            shipper.setAge(age);
            shipper.setLicenseId(licenseId);
            shipper.setCardId(cardId);
            shipper.setDriverId(driverId);
            shipper.setOrigin(origin);

            //将实体类插入数据库
            shipperService.insert(shipper);
            List<String> tran = new ArrayList<>();
            if (tranVan.equals("否")) {
                tran.add(tranElectricMotor);
            } else if (tranElectricMotor.equals("否")) {
                tran.add(tranVan);
            } else {
                tran.add(tranVan);
                tran.add(tranElectricMotor);
            }
            Integer maxId = shipperService.selectMaxId();
            tranService.insert(maxId, tran);

        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("文件导入成功");
        return jsonResult;
    }
}
